/**
 * Project: uambank-webapp
 * 
 * File Created at 2011-8-24
 * $Id$
 * 
 * Copyright 2008 6677bank.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * 6677bank Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with 6677bank.com.
 */
package com.liyue.interceptor;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.liyue.exception.BusinessException;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 展现层统一异常处理类，供错误消息提示
 * 
 * @author liyue
 * @version ErrorHandlingInterceptor.java 2011-8-24 下午02:39:22
 */
public class ErrorHandlingInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 2069071061195269040L;

    private static Logger     LOG              = Logger.getLogger(ErrorHandlingInterceptor.class);

    /**
     * 将各种异常分类输出，可以配置多个异常类
     */
    @Override
    public String intercept(ActionInvocation invocation) {
        try {
            return invocation.invoke();
        } catch (BusinessException e) {
            ///业务异常///
            handleException(e, invocation);
            return "businessError";
        } catch (Exception e) {
            ///其他异常///
            handleException(e, invocation);
        }
        return "error";
    }

    /**
     * @param e
     * @param invocation
     */
    private void handleException(Exception e, ActionInvocation invocation) {
        ActionSupport action = (ActionSupport) invocation.getAction();
        List<String> errors = new ArrayList<String>();
        errors.add(e.getMessage());
        action.setActionErrors(errors);

        /////将异常信息加入Log中////
        StackTraceElement[] traces = e.getStackTrace();
        StringBuffer traceLog = new StringBuffer(e.getMessage() != null ? e.getMessage() : "");
        traceLog.append("\n\t");
        for (StackTraceElement trace : traces) {
            traceLog.append(trace.toString()).append("\n\tat ");
        }
        traceLog.append("... more");
        LOG.error(traceLog.toString());
    }

}
